<template>
  <div>
    <a-affix>
      <a-page-header
          style="border: 1px solid rgb(235, 237, 240);z-index: 3;"
          :ghost="false"
          :title="(exam && exam.title) || '比赛'"
          :sub-title="description"
          @back="goHome"
      >
        <template slot="extra" v-if="exam">
          <a-button key="1" type="primary" @click="onHandPaper">
            交卷
          </a-button>
        </template>
        <a-row type="flex">
          <a-statistic title="已完成" suffix="道" :value="finished + '/' + questions.length" style="margin: 0 32px;"/>
          <a-statistic title="剩余时间" :value="remaining" style="margin: 0 32px;"/>
        </a-row>
        <template slot="footer">
          <a-progress :percent="(questions.length > 0 ? (finished / questions.length * 100) : 0).toFixed(2)" size="small" status="active" />
        </template>
      </a-page-header>
    </a-affix>
      <a-layout>
        <a-layout-content style="padding: 10px;min-height: calc(100vh - 160px);">
          <a-card hoverable style="max-width: 1000px; margin: 10px auto 50px auto;">
            <a-skeleton active :paragraph="{ rows: 24 }" v-if="questions.length === 0 && loading" />

            <div v-if="fills.length > 0">
              <h3 id="fill" class="q-type-title">填空题({{fills.length}}道, 每题{{(exam && exam.fillScore) || 0}}分)</h3>
              <div class="q-box" v-for="(fill, index) in fills" v-bind:key="fill.id">
                <h4 class="q-title" :id="'q' + fill.id">{{ index + 1 }}. {{ fill.title }}</h4>
                <a-input addon-before="请输入" v-model="fill.answer" @change="onAnswer(fill.id)"></a-input>
              </div>
            </div>

            <div v-if="judges.length > 0">
              <h3 id="judge" class="q-type-title">判断题({{judges.length}}道, 每题{{(exam && exam.judgeScore) || 0}}分)</h3>
              <div class="q-box" v-for="(judge, index) in judges" v-bind:key="judge.id">
                <h4 class="q-title" :id="'q' + judge.id">{{ index + 1 + fills.length}}. {{ judge.title }}</h4>
                <a-radio-group v-model="judge.answer" @change="onAnswer(judge.id)">
                  <a-radio style="display: block;line-height: 30px;" :value="true">
                    正确
                  </a-radio>
                  <a-radio style="display: block;line-height: 30px;" :value="false">
                    错误
                  </a-radio>
                </a-radio-group>
              </div>
            </div>

            <div v-if="radios.length > 0">
              <h3 id="radio" class="q-type-title">单选题({{radios.length}}道, 每题{{(exam && exam.radioScore) || 0}}分)</h3>
              <div class="q-box" v-for="(radio, index) in radios" v-bind:key="radio.id">
                <h4 class="q-title" :id="'q' + radio.id">{{ index + 1 + fills.length + radios.length }}. {{ radio.title }}</h4>
                <a-radio-group v-model="radio.answer" @change="onAnswer(radio.id)">
                  <a-radio class="radio-option-box" :value="option.key" v-for="option in radio.options" v-bind:key="option.key">
                    {{ option.text }}
                  </a-radio>
                </a-radio-group>
              </div>
            </div>

            <div v-if="multiples.length > 0">
              <h3 id="multiple" class="q-type-title">多选题({{multiples.length}}道, 每题{{(exam && exam.multipleScore) || 0}}分)</h3>
              <div class="q-box" v-for="(multiple, index) in multiples" v-bind:key="multiple.id">
                <h4 class="q-title" :id="'q' + multiple.id">{{ index + 1 + fills.length + radios.length + multiples.length }}. {{ multiple.title }}</h4>
                <a-checkbox-group v-model="multiple.answer" @change="onAnswer(multiple.id)">
                  <div class="multiple-option-box" v-for="option in multiple.options" v-bind:key="option.key">
                    <a-checkbox :value="option.key">{{ option.text }}</a-checkbox>
                  </div>
                </a-checkbox-group>
              </div>
            </div>
          </a-card>
        </a-layout-content>
        <a-layout-sider breakpoint="lg" collapsedWidth="0" width="200" style="background-color: white;">
          <a-anchor :offsetTop="160">
            <a-anchor-link href="#fill" v-if="fills.length > 0">
              <h3 slot="title">
                <span v-if="fills.filter(f=>f.finish).length >= fills.length" style="color: #42b983"><a-icon type="check-circle" /></span><span> 填空题</span>
              </h3>
              <a-anchor-link :href="'#q' + fill.id" v-for="(fill, index) in fills" v-bind:key="fill.id">
                <template slot="title">
                  <span><span v-if="fill.finish" style="color: #42b983"> <a-icon type="check-circle" /></span> {{'第' + (index + 1) + '题'}}</span>
                </template>
              </a-anchor-link>
            </a-anchor-link>
            <a-anchor-link href="#judge" v-if="judges.length > 0">
              <h3 slot="title">
                <span v-if="judges.filter(f=>f.finish).length >= judges.length" style="color: #42b983"><a-icon type="check-circle" /></span><span> 判断题</span>
              </h3>
              <a-anchor-link :href="'#q' + judge.id" v-for="(judge, index) in judges" v-bind:key="judge.id">
                <template slot="title">
                  <span><span v-if="judge.finish" style="color: #42b983"> <a-icon type="check-circle" /></span> {{'第' + (index + 1 + fills.length) + '题'}}</span>
                </template>
              </a-anchor-link>
            </a-anchor-link>
            <a-anchor-link href="#radio" v-if="radios.length > 0">
              <h3 slot="title">
                <span v-if="radios.filter(f=>f.finish).length >= radios.length" style="color: #42b983"><a-icon type="check-circle" /></span><span> 单选题</span>
              </h3>
              <a-anchor-link :href="'#q' + radio.id" v-for="(radio, index) in radios" v-bind:key="radio.id">
                <template slot="title">
                  <span><span v-if="radio.finish" style="color: #42b983"> <a-icon type="check-circle" /></span> {{'第' + (index + 1 + fills.length + judges.length) + '题'}}</span>
                </template>
              </a-anchor-link>
            </a-anchor-link>
            <a-anchor-link href="#multiple" v-if="multiples.length > 0">
              <h3 slot="title">
                <span v-if="multiples.filter(f=>f.finish).length >= multiples.length" style="color: #42b983"><a-icon type="check-circle" /></span><span> 多选题</span>
              </h3>
              <a-anchor-link :href="'#q' + multiple.id" v-for="(multiple, index) in multiples" v-bind:key="multiple.id">
                <template slot="title">
                  <span><span v-if="multiple.finish" style="color: #42b983"> <a-icon type="check-circle" /></span> {{'第' + (index + 1 + fills.length + judges.length + radios.length) + '题'}}</span>
                </template>
              </a-anchor-link>
            </a-anchor-link>
          </a-anchor>
        </a-layout-sider>
      </a-layout>
    <a-back-top />
  </div>
</template>

<script>
import global from "@/components/global";

export default {
  name: "exam",
  data(){
    return {
      loading: false,
      exam: null,
      paper: null,
      questions: [],
      fills: [],
      judges: [],
      radios: [],
      multiples: [],
      remaining: '00:00:00',
    }
  },
  methods:{
    onHandPaper(){
      let that = this
      let tip = ''
      if(this.finished < this.questions.length){
        tip = `还有${this.questions.length - this.finished}题未完成, `
      }
      this.$confirm({
        title: '提示',
        content: tip + `你确定要交卷吗?`,
        okText: '确定',
        cancelText: '取消',
        onOk() {
          that.handPaper()
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    },
    handPaper(){
      let that = this
      global.http(this, 'api/Exam/HandPaper?id=' + this.paper.id, {
        successText: '',
        success(){
          let secondsToGo = 3;
          const modal = that.$success({
            title: '提示',
            content: `交卷成功，页面将在 ${secondsToGo} 秒后回到主页。`,
            okText: '知道啦',
            onOk() {
              window.location = '/home'
            }
          });
          const interval = setInterval(() => {
            secondsToGo -= 1;
            modal.update({
              content: `交卷成功，页面将在 ${secondsToGo} 秒后回到主页。`,
            });
          }, 1000);
          setTimeout(() => {
            clearInterval(interval);
            modal.destroy();
            window.location = '/home'
          }, secondsToGo * 1000);
        }
      })
    },
    onAnswer(qid){
      let that = this
      let question = this.questions.filter(q => q.id === qid)[0]
      if (question && question.answer !== null && question.answer !== ''){
        let postData = {
          paperQuestionId: question.id,
          answer: question.answer
        }
        if(question.type === 2){
          if(question.answer.length > 1){
            postData.answer = JSON.parse(JSON.stringify(question.answer))
            postData.answer.sort()
            postData.answer = JSON.stringify(postData.answer)
          }else {
            return
          }
        }else if(question.type !== 3){
          if(question.answer !== ''){
            postData.answer = JSON.stringify(question.answer)
          }else {
            return
          }
        }
        global.http(this, 'api/Exam/Answer', {
          data: postData,
          successText: '',
          failText: '答案提交失败',
          success(){
            question.finish = true
          },
          fail(res){
            if(res.status === 2){
              that.handPaper()
            }
          }
        })
      }
    },
    loadData(){
      let id = this.$route.query.exam
      let that = this
      that.loading = true
      global.http(this, 'api/Exam/Paper?id=' + id, {
        success(res){
          res.data.questions.sort((a, b) => a.id - b.id)
          that.exam = res.data.examination
          that.paper = res.data.paper
          let questions = res.data.questions
          for(let i = 0; i < questions.length; i++){
            if(questions[i].type === 1 || questions[i].type === 2){
              let options = [{key: 0, text: questions[i].option1}]
              options.push({key: 1, text: questions[i].option2})
              options.push({key: 2, text: questions[i].option3})
              options.push({key: 3, text: questions[i].option4})
              if(that.exam.randomOptions){
                let orders = questions[i].optionsOrder.split(',').map(v=>Number(v))
                questions[i].options = [options[orders[0]], options[orders[1]], options[orders[2]], options[orders[3]]]
              }
            }
            if(questions[i].type !== 3 && questions[i].answer !== null){
              questions[i].answer = JSON.parse(questions[i].answer)
            }
            questions[i].finish = questions[i].answer !== null
          }
          that.questions = questions
          that.fills = that.questions.filter(x=>x.type === 3)
          that.judges = that.questions.filter(x=>x.type === 0)
          that.radios = that.questions.filter(x=>x.type === 1)
          that.multiples = that.questions.filter(x=>x.type === 2)
          setInterval(function (){
            let now = new Date()
            let s = that.exam.time * 60 - (now.getTime() - new Date(that.paper.startTime).getTime()) / 1000
            if(s >= 0){
              that.remaining = global.sToHms(s)
            }
            if(s === 60){
              this.$notification.warning({
                message: '提示',
                description:
                    '距离比赛结束只有1分钟了。',
              });
            }
            if(that.remaining === '00:00:00'){
              that.handPaper()
            }
          }, 1000)
        },
        complete(){
          that.loading = false
        }
      })
    },
    goHome(){
      if(this.exam){
        this.$confirm({
          title: '提示',
          content: '确定离开比赛吗',
          okText: '确定',
          cancelText: '取消',
          onOk() {
            window.location = '/home'
          },
        });
      }else {
        window.location = '/home'
      }
    }
  },
  computed:{
    finished(){
      return this.questions.filter(x=>x.finish).length
    },
    description(){
      if(this.exam){
        return `时间: ${global.dateToMdDay(this.exam.startTime)} ${global.dateToHm(this.exam.startTime)} ~ ${global.dateToHm(this.exam.endTime)}`
      }
      return ''
    }
  },
  mounted() {
    this.loadData()
  }
}
</script>

<style>
.q-type-title{
  margin:30px 1em 20px 1em;
  color: cornflowerblue;
}

.q-title{
  font-weight: bold;
}

.q-box{
  margin: 0 2em 30px 2em;
}

.multiple-option-box{
  line-height: 2em;
}

.radio-option-box{
  display: block;
  line-height: 30px;
}

.demo-loadmore-list {
  min-height: 350px;
}

/* 设置滚动条的样式 */
::-webkit-scrollbar {
  width:8px;
}
/* 滚动槽 */
::-webkit-scrollbar-track {
  background-color: white;
  border-radius:4px;
}
/* 滚动条滑块 */
::-webkit-scrollbar-thumb {
  border-radius:4px;
  background:rgba(0,0,0,0.2);
}
::-webkit-scrollbar-thumb:window-inactive {
  background: white;
}
</style>